<template>
  <!-- 展开/收缩的图标 -->
  <el-icon style="font-size: 26px;cursor: pointer" v-if="collapseIcon" @click="handleCollapse">
    <Fold/>
  </el-icon>
  <el-icon style="font-size: 26px;cursor: pointer" v-else @click="handleCollapse">
    <Expand/>
  </el-icon>
  <!-- 面包屑 -->


  <!-- 个人头像及下拉选项 -->
  <div class="personal">

    <!--  全屏和退出全屏  -->
    <span
        v-if="flag"
        class="iconfont-myicons"
        style="font-size: 30px; margin-right: 5px; cursor: pointer;"
        @click="handleFullScreen">&#xeb11;
    </span>
    <span
        v-else
        class="iconfont-myicons"
        style="font-size: 30px; margin-right: 5px; cursor: pointer;"
        @click="handleFullScreen">&#xeb10;
    </span>

    <el-dropdown @command="handleCommand">
      <!-- 头像按钮 -->
      <span class="el-dropdown-link" style="display: flex;align-items: center">
      <el-avatar :src="pageData.avatar" class="avatar"></el-avatar>
        <span>{{ data.nickname }}</span>
    </span>

      <!-- 下拉菜单项 -->
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="settings">设置</el-dropdown-item>
          <el-dropdown-item v-if="data.roles === 'Zuser' || data.roles === 'Tuser'" divided command="serviceSwitching">
            业务切换
          </el-dropdown-item>
          <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>


<script setup>
import {mainStore} from '../stores/main.js'
import {onMounted, onUnmounted, reactive, ref} from 'vue';
import {Expand, Fold} from '@element-plus/icons-vue'
import {ElAvatar, ElDropdown, ElDropdownItem, ElDropdownMenu, ElIcon, ElMessageBox} from 'element-plus'
import {useRouter} from "vue-router/dist/vue-router";
import request from "@/utils/request.js";

const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const data = dataString ? JSON.parse(dataString) : null;
const userRoles = JSON.parse(localStorage.getItem('userRoles'))

const pageData = reactive({
  avatar: '',
  nickname:'',
})

//1、控制菜单栏伸展和收缩
const Store = mainStore()
const collapseIcon = ref(true);
const handleCollapse = () => {
  Store.changeCollapse();
  Store.changeAsideWidth();
  collapseIcon.value = collapseIcon.value !== true;
}

// 2、处理头像下面的菜单项点击事件
const router = useRouter();
const handleCommand = (command) => {
  console.log('点击的命令是: ', command);
  if (command === 'logout') {
    // 弹出确认对话框
    ElMessageBox.confirm(
        '是否确认退出登录？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(() => {
      // 用户点击确认退出
      sessionStorage.clear(); // 清除 session 数据
      localStorage.clear(); // 清除 localStorage 数据
      router.push("/login"); // 导航到登录页面
    }).catch(() => {
      // 用户取消注销或关闭对话框，可在此处理相应逻辑
      // 例如，不执行任何操作或给出用户反馈
    });
  }
  if (command === 'settings') {
    goToSetting()
  }

  if (command === 'serviceSwitching') {
    serviceSwitching()
  }
};


//3、以下代码监听全屏和退出全屏的状态
const flag = ref(false);
const handleFullScreen = () => {
  if (!document.fullscreenElement) {
    flag.value = true; // 即将请求进入全屏
    document.documentElement.requestFullscreen().catch((e) => {
      flag.value = false; // 如果请求失败，则保持flag为false
    });
  } else {
    flag.value = false; // 即将退出全屏
    document.exitFullscreen().catch((e) => {
      flag.value = true; // 如果退出失败，则保持flag为true
    });
  }
};

// 监听全屏状态变化事件
const onFullScreenChange = () => {
  flag.value = !!document.fullscreenElement;
};

onMounted(() => {
  document.addEventListener('fullscreenchange', onFullScreenChange);
});

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', onFullScreenChange);
});

const goToSetting = () => {
  // 导航到设置页面
  router.push("/setting")
}

const serviceSwitching = () => {
  if (data.roles === 'Tuser') {
    data.roles = 'Zuser';
    data.descriptions = '招标人员';
    data.roleIds = 3;
    // 将修改后的 data 对象转换为字符串，并存储回 localStorage 中
    localStorage.setItem('data', JSON.stringify(data));
    // console.log(data)
    // console.log(userRoles)
    userRoles[0] = 'Zuser';
    // 将修改后的 userRoles 数组转换为字符串，并存储回 localStorage 中
    localStorage.setItem('userRoles', JSON.stringify(userRoles));
    updateToZuser();
  } else {
    data.roles = 'Tuser';
    data.descriptions = '投标人员';
    data.roleIds = 4;
    // 将修改后的 data 对象转换为字符串，并存储回 localStorage 中
    localStorage.setItem('data', JSON.stringify(data));
    // console.log(data)
    // console.log(userRoles)
    userRoles[0] = 'Tuser';
    // 将修改后的 userRoles 数组转换为字符串，并存储回 localStorage 中
    localStorage.setItem('userRoles', JSON.stringify(userRoles));
    updateToTuser();
  }
}


const updateToZuser = () => {
  const entity = {
    userId: data.userId,
    roleId: 3,
    isDeleted: 0
  }
  request.put(`/user/roles/edit?oldRoleId=4`, entity).then((res) => {
    console.log("编辑成功返回信息：", res);
    location.href = '/index';
  })
}

const updateToTuser = () => {
  const entity = {
    userId: data.userId,
    roleId: 4,
    isDeleted: 0
  }

  request.put(`/user/roles/edit?oldRoleId=3`, entity).then((res) => {
    console.log("编辑成功返回信息：", res);
    location.href = '/index';
  })
}

const LoadUserAvatar = () => {
  request.get(`/user/getUserAvatarAndNickname/${data.userId}`).then((res) => {
    console.log("头部信息",res)
    pageData.avatar = res.data[0].avatar;
    pageData.nickname = res.data[0].nickname;
  })
}

LoadUserAvatar();

</script>

<style scoped>
.personal {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.avatar {
  width: 40px;
  height: 40px;
  margin-right: 2px;
}
</style>